package com.hong.springboot.config;

import com.sproutsocial.nsq.Publisher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


@Service
@Slf4j
public class NsqProducer {

    @Value("${springboot.msq.url}")
    private String url;

    private Publisher publisher;


    @PostConstruct
    public void init(){
        publisher = new Publisher(url);
    }
    @PreDestroy
    public void close(){
        try {
            if(null!= publisher){
                publisher.stop();
            }
        }catch (Exception e){
            log.error("关闭失败{}",e);
        } catch (Throwable throwable) {
            log.error("关闭失败{}",throwable);
            throwable.printStackTrace();
        }
    }

    public Boolean send(String msg,String topic)  {
        try {
            publisher.publishBuffered(topic,msg.getBytes());
            return true;
        }catch (Exception e){
            log.error("发送失败{}",e);
        }
        return false;
    }
}